import React, { Component } from "react";

import {
  Button,
  ButtonToolbar,
  Panel,
  Grid,
  Row,
  Col,
  Input,
  Icon,
  Table,
  Modal,
  Form,
  CheckTreePicker,
  Schema,
  Alert,
} from "rsuite";

import moment from "moment";
import CustomField from "../../../components/form/customField";
import http from "../../../components/http/http";
import rest from "../../../assets/config/rest.json";

class Role extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "Role",
      showModal: false,
      tableLoading: false,
      table: {
        code: "",
        data: [],
      },
      form: {
        id: "",
        code: "",
        menuIds: [],
      },
      menus: [],
      checkModel: this.checkModel(),
      currentPermits: [],
    };
    this.loadMenus = this.loadMenus.bind(this);
    this.loadLimits = this.loadLimits.bind(this);
    this.createLimit = this.createLimit.bind(this);
    this.updateLimit = this.updateLimit.bind(this);
    this.deleteLimit = this.deleteLimit.bind(this);
    this.submitLimit = this.submitLimit.bind(this);
    this.treeSelect = this.treeSelect.bind(this);
  }

  UNSAFE_componentWillMount() {
    let menus = localStorage.getItem(rest.menu);
    if (!!menus) {
      this.setState({
        currentPermits: JSON.parse(menus)
          .filter((x) => x.name === "System")[0]
          .children.filter((y) => y.name === "Role")[0].permits,
      });
    }
    this.loadMenus();
    this.loadLimits();
  }

  componentDidMount() {}

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  checkModel() {
    const { StringType, ArrayType } = Schema.Types;
    return Schema.Model({
      code: StringType().isRequired("This field is required."),
      menuIds: ArrayType().isRequired("This field is required."),
    });
  }

  loadMenus() {
    http.get(rest.menuList).then((response) => {
      if (response.status === 200) {
        this.setState({ menus: response.data });
      }
    });
  }

  loadLimits() {
    const { table } = this.state;
    this.setState({ tableLoading: true });
    http
      .get(rest.roles, {
        params: {
          code: table.code,
        },
      })
      .then((response) => {
        if (response.status === 200) {
          let result = response.data.map((x) => {
            x.createTime = moment(x.createTime).format("YYYY-MM-DD HH:mm:ss");
            return x;
          });
          this.setState({
            tableLoading: false,
            table: {
              ...table,
              data: result,
            },
          });
        }
      });
  }

  createLimit() {
    this.setState({
      showModal: true,
      form: {
        id: "",
        code: "",
        menuIds: [],
      },
    });
  }

  updateLimit(rowData) {
    this.setState({
      showModal: true,
      form: {
        id: rowData.id,
        code: rowData.code,
        menuIds: rowData.menuIds,
      },
    });
  }

  deleteLimit(id) {
    http.delete(`${rest.role}/${id}`).then((response) => {
      if (response.status === 200) {
        Alert.success("操作成功!");
        this.setState({ showModal: false });
        this.loadLimits();
      } else {
        Alert.error("操作失败!");
      }
    });
  }

  submitLimit() {
    const { form } = this.state;
    const { limitForm } = this.refs;
    let callback = (response) => {
      if (response.status === 200) {
        Alert.success("操作成功!");
        this.setState({ showModal: false });
        this.loadLimits();
      } else {
        Alert.error("操作失败!");
      }
    };
    limitForm.checkAsync().then((result) => {
      if (result.hasError) {
        return;
      }
      if (!!form.id) {
        http
          .put(rest.role, {
            id: form.id,
            code: form.code,
            menuIds: form.menuIds,
          })
          .then(callback);
      } else {
        http
          .post(rest.role, {
            code: form.code,
            menuIds: form.menuIds,
          })
          .then(callback);
      }
    });
  }

  treeSelect(node, values) {
    const { form } = this.state;
    this.setState({
      form: {
        ...form,
        menuIds: values,
      },
    });
  }

  render() {
    const {
      title,
      table,
      showModal,
      form,
      checkModel,
      menus,
      tableLoading,
      currentPermits,
    } = this.state;
    return (
      <Grid fluid>
        <Panel header={title}>
          <Panel
            header={<Icon icon="search"> 查询条件</Icon>}
            style={{ background: "#fff" }}
            collapsible
            bordered
            defaultExpanded
          >
            <Row>
              <Col xs={4}>
                <Input
                  value={table.code}
                  onChange={(e) => {
                    this.setState({
                      table: {
                        ...table,
                        code: e,
                      },
                    });
                  }}
                  placeholder="请输入权限名称"
                />
              </Col>
              <Col>
                <ButtonToolbar>
                  <Button color="blue" onClick={this.loadLimits}>
                    <Icon icon="search-peoples" /> 查询
                  </Button>
                  <Button
                    color="orange"
                    onClick={() => {
                      this.setState(
                        {
                          table: {
                            ...table,
                            code: "",
                          },
                        },
                        () => {
                          this.loadLimits();
                        }
                      );
                    }}
                  >
                    <Icon icon="reload" /> 重置
                  </Button>
                  {currentPermits.indexOf("system:role:c") !== -1 ? (
                    <Button color="green" onClick={this.createLimit}>
                      <Icon icon="plus" /> 新建
                    </Button>
                  ) : null}
                </ButtonToolbar>
              </Col>
            </Row>
          </Panel>
          <Panel
            header="权限列表"
            style={{ marginTop: "1rem", background: "#fff" }}
            bordered
          >
            <Row>
              <Col>
                <Table
                  autoHeight={true}
                  data={table.data}
                  loading={tableLoading}
                >
                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>Id</Table.HeaderCell>
                    <Table.Cell dataKey="id" />
                  </Table.Column>
                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>角色名称</Table.HeaderCell>
                    <Table.Cell dataKey="code" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>创建时间</Table.HeaderCell>
                    <Table.Cell dataKey="createTime" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>操作</Table.HeaderCell>

                    <Table.Cell>
                      {(rowData) => {
                        return (
                          <ButtonToolbar>
                            {currentPermits.indexOf("system:role:u") !== -1 ? (
                              <Button
                                color="blue"
                                size="xs"
                                onClick={() => {
                                  this.updateLimit(rowData);
                                }}
                              >
                                <Icon icon="edit" /> 编辑
                              </Button>
                            ) : null}
                            {currentPermits.indexOf("system:role:d") !== -1 ? (
                              <Button
                                color="red"
                                size="xs"
                                onClick={() => {
                                  this.deleteLimit(rowData.id);
                                }}
                              >
                                <Icon icon="trash2" /> 删除
                              </Button>
                            ) : null}
                          </ButtonToolbar>
                        );
                      }}
                    </Table.Cell>
                  </Table.Column>
                </Table>
              </Col>
            </Row>
          </Panel>
        </Panel>
        <Modal
          size="sm"
          show={showModal}
          onHide={() => {
            this.setState({ showModal: false });
          }}
        >
          <Modal.Header>
            <Modal.Title>新增/编辑用户</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form
              fluid
              ref="limitForm"
              onChange={(form) => {
                this.setState({ form: form });
              }}
              formValue={form}
              model={checkModel}
            >
              <CustomField
                name="code"
                label="角色名称"
                accepter={Input}
                placeholder="请输入角色名称"
                type="text"
              />
              <CustomField
                name="menuIds"
                label="选择权限:"
                block={true}
                searchable={false}
                accepter={CheckTreePicker}
                labelKey="name"
                valueKey="id"
                childKey="children"
                data={menus}
                value={form.menuIds}
                onSelect={this.treeSelect}
                cascade={false}
              />
            </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.submitLimit} appearance="primary">
              确认
            </Button>
            <Button
              onClick={() => {
                this.setState({ showModal: false });
              }}
              appearance="subtle"
            >
              取消
            </Button>
          </Modal.Footer>
        </Modal>
      </Grid>
    );
  }
}

export default (props) => <Role {...props} key={props.location.pathname} />;
